﻿'Imports MySql.Data.MySqlClient
'Imports System.Data
Imports System
Imports System.Net
Imports System.IO
Imports Microsoft.Win32
Imports Microsoft.Win32.Registry
Imports Microsoft.Win32.RegistryKey

Public Class frmDownload
    'This class holds the entire donwload code

    'make sure the authentication cookies are accessable from all methods in the class
    Public cookies As New CookieCollection

    'holds the class name of the current class
    Dim classname As String

    'holds the assignment name of the current assignment
    Dim assignmentname As String

    'holds the userid of the current studend being downloaded
    Dim userid As String

    'holds weather the  classes were downloaded yet
    Public downloadedClasses As Boolean

    'holds a list of courseids for the logged on user
    Public courseids As New List(Of String)

    Public courses As New List(Of Course)


    '---------------------------------------------------------------------

    Public Enum HTTPMethod As Short
        'Enumerate the HTTP_GET and HTTP_POST methods
        HTTP_GET = 0
        HTTP_POST = 1
    End Enum


    'Now handled by lst_assignment_selectedindexchange

    'Private Sub lstAssignment_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lstAssignment.Click

    '    assignmentname = lstAssignment.SelectedItem
    '    If assignmentname = "" Then
    '        cmdDownload.Enabled = False
    '        cmdDownload.ForeColor = Color.DimGray
    '    Else
    '        cmdDownload.Enabled = True
    '        cmdDownload.ForeColor = Color.Black
    '    End If
    '    Call showCollected()
    'End Sub



    Private Sub frmDownload_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
        frmMain.Show()
        frmMain.Activate()
    End Sub

    Private Sub frmDownload_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        'Populate lstClass with all classes of the logged in user
        'System.Threading.Thread.Sleep(1000)

        'downloadedClasses = False 'prevents loading classes in the lstClass more than once (mainly used from frmMain)
        'userid = frmSplash.userid

    End Sub

    Public Sub getclasses()

        Me.Refresh()




        If (frmSplash.httplog.isAuthenticated() = False) Then
            MsgBox("ERROR")
        End If


        courses = frmSplash.httplog.getClasses()
        Dim i = 0
        While (courses.Count > i)
            lstClass.Items.Add(courses.Item(i).getname())
            i += 1
        End While

        Me.Show()
        Me.Refresh()




















        ''sets lstclasses to all of the logged in users courses


        ''holds the SQL query commands
        'Dim contextSQL
        'Dim classSQL
        'Dim courseSQL
        'Dim coursenameSQL

        ''holds the context ids for context level 50
        'Dim contexts As New List(Of String)

        ''holds the course context ids for this user
        'Dim coursecontextid As New List(Of String)

        ''holds the course ids for the logged in user
        'Dim coursenumbers As New List(Of String)

        ''holds the course names for the logged in user
        'Dim coursenames As New List(Of String)

        ''general use counter variables
        'Dim p As Integer
        'Dim g As Integer


        ''holds the SQL server connection
        'Dim mysqlServer As MySqlConnection

        ''holds the SQL query before execution and handles command execution
        'Dim myCommand As New MySqlCommand

        ''create a new mysqlconnection object
        'mysqlServer = New MySqlConnection()

        ''set the connection string to the one defined in frmSplash
        'mysqlServer.ConnectionString = frmSplash.SQLConnection1.getConnectionString

        ''set the SQL command to find all the contexts at context lvl 50
        'contextSQL = "select id from mdl_context where contextlevel = 50"



        'Try

        '    'open the SQL connection
        '    mysqlServer.Open()


        '    Try

        '        'set the SQL query and assign the mysql server connection that it will be executed on
        '        myCommand.Connection = mysqlServer
        '        myCommand.CommandText = contextSQL

        '        'create a mysql data reader and execute it
        '        Dim reader As MySqlDataReader
        '        reader = myCommand.ExecuteReader()

        '        'read the resaults of the query
        '        While reader.Read()
        '            contexts.Add(reader.GetString(0))
        '        End While

        '        'close the reader
        '        reader.Close()


        '        'while there are still contexts to check
        '        While (contexts.Count() > 0)


        '            'set the SQL command for each context
        '            classSQL = "select roleid from mdl_role_assignments where contextid = " & contexts.Item(0) & _
        '            " and userid = " & userid

        '            'set the SQL query and assign the mysql server connection that it will be executed on
        '            myCommand.Connection = mysqlServer
        '            myCommand.CommandText = classSQL

        '            'execute the command and prepare to read the results
        '            reader = myCommand.ExecuteReader()

        '            'read the results of the query
        '            While reader.Read()
        '                coursecontextid.Add(contexts.Item(0))
        '            End While

        '            'close the reader
        '            reader.Close()

        '            'remove the current context as were done with it
        '            contexts.RemoveAt(0)
        '        End While

        '        'clear p
        '        p = 0

        '        'for each course context ids
        '        While (coursecontextid.Count() > p)

        '            'set the SQL query for each course context id
        '            courseSQL = "select instanceid from mdl_context where id = " & coursecontextid.Item(p)

        '            'set the SQL query and assign the mysql server connection that it will be executed on
        '            myCommand.Connection = mysqlServer
        '            myCommand.CommandText = courseSQL

        '            'execute the command and prepare to read the results
        '            reader = myCommand.ExecuteReader()

        '            'read the results of the query
        '            While reader.Read()
        '                coursenumbers.Add(reader.GetString(0))
        '            End While

        '            'close the reader
        '            reader.Close()

        '            'incrment the counter variable
        '            p += 1
        '        End While

        '        'clear p
        '        p = 0

        '        'for each course number get the full course name
        '        While (coursenumbers.Count() > p)

        '            'set the SQL command for each query
        '            coursenameSQL = "select fullname from mdl_course where id = " & coursenumbers.Item(p)

        '            'set the SQL query and assign the mysql server connection that it will be executed on
        '            myCommand.Connection = mysqlServer
        '            myCommand.CommandText = coursenameSQL

        '            'execute the command and prepare to read the results
        '            reader = myCommand.ExecuteReader()

        '            'read the reaults of the query
        '            While reader.Read()
        '                coursenames.Add(reader.GetString(0))
        '            End While

        '            'close the reader
        '            reader.Close()

        '            'increment the counter
        '            p += 1
        '        End While

        '        'close the mysql server connection
        '        mysqlServer.Close()


        '        'catch all reader errors
        '    Catch myerror As MySqlException
        '        MsgBox("There was an error reading from the database: " & myerror.Message)
        '    End Try

        '    'catch mysql server connection Errors
        'Catch myerror As MySqlException
        '    MessageBox.Show("Error connecting to the database: " & myerror.Message)

        '    'if the connection is not closed close it
        'Finally
        '    If mysqlServer.State <> ConnectionState.Closed Then mysqlServer.Close()
        'End Try

        ''clear g
        'g = 0

        ''check to see if there are any duplict courses
        ''add the courses to lstclass and add the course ids to the global variable courseids
        'While (coursenames.Count() - 1 > g)
        '    If (coursenames.Item(g + 1) <> coursenames.Item(g)) Then
        '        courseids.Add(coursenumbers.Item(g))
        '        lstClass.Items.Add(coursenames.Item(g))
        '    End If
        '    g += 1
        'End While

        ''add the last course to lstclass and last course id to the global variable courseids 
        'If (coursenames.Count < 0) Then
        '    lstClass.Items.Add(coursenames.Item(coursenames.Count() - 1))
        '    courseids.Add(coursenumbers.Item(coursenames.Count() - 1))
        'End If

    End Sub

    Private Sub cmdFinished_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdFinshed.Click
        'hides the current form and shows and focues the main form

        lstClass.Items.Clear()

        Me.Hide()

        frmMain.Show()
        frmMain.Activate()
        frmMain.Refresh()
        frmMain.Focus()
        frmMain.TopMost = True
    End Sub

    Private Sub lstClass_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lstClass.SelectedIndexChanged
        progressBar.Value = progressBar.Minimum

        Dim i As Integer = 0
        Dim f As Integer = 0
        lstAssignment.Items.Clear()
        'MsgBox(courses.Item(0).getassignmentlist.Item(0))

        While (courses.Count > i)
            'MsgBox(lstClass.Items.Item(lstClass.SelectedIndex) & " " & courses.Item(i).getname)
            If (lstClass.Items.Item(lstClass.SelectedIndex) = courses.Item(i).getname) Then
                'MsgBox(i)
                While (courses.Item(i).getassignmentlist.Count > f)
                    'MsgBox(i)
                    lstAssignment.Items.Add(courses.Item(i).getassignmentlist.Item(f).getassignmentname())
                    f += 1
                End While
                f = 0
            End If
            i += 1
        End While



        '    'when the selected class changes
        '    'change lstassignment to the right assignments

        '    'holds the assignment SQL command
        '    Dim assignmentSQL As String

        '    'holds the current list of assignments for the selected course
        '    Dim assignmentnames As New List(Of String)

        '    'general use counter variables
        '    Dim p As Integer


        '    'holds the SQL server connection
        '    Dim mysqlServer As MySqlConnection

        '    'holds the SQL query before execution and handles command execution
        '    Dim myCommand As New MySqlCommand


        '    'clear the current list of assignments
        '    lstAssignment.Items.Clear()

        '    'disable the download button untill an assignment is selected
        '    cmdDownload.Enabled = False
        '    cmdDownload.ForeColor = Color.DimGray


        '    'create a new mysqlconnection object
        '    mysqlServer = New MySqlConnection()

        '    'set the connection string to the one defined in frmSplash
        '    mysqlServer.ConnectionString = frmSplash.SQLConnection1.getConnectionString


        '    'only run the SQL if somthing is selected
        '    If lstClass.SelectedIndex <> -1 Then

        '        'set the SQL command
        '        assignmentSQL = "select name from mdl_assignment where course = " & courseids.Item(lstClass.SelectedIndex)

        '        Try

        '            'open the SQL server connection
        '            mysqlServer.Open()

        '            Try
        '                'set the SQL query and assign the mysql server connection that it will be executed on
        '                myCommand.Connection = mysqlServer
        '                myCommand.CommandText = assignmentSQL

        '                'create a mysql data reader and execute it
        '                Dim reader As MySqlDataReader
        '                reader = myCommand.ExecuteReader()


        '                'read the results of the query
        '                While reader.Read()
        '                    assignmentnames.Add(reader.GetString(0))
        '                End While

        '                'close the reader
        '                reader.Close()

        '                'close the mysql connection
        '                mysqlServer.Close()


        '                'catch all reader errors
        '            Catch myerror As MySqlException
        '                MsgBox("There was an error reading from the database: " & myerror.Message)
        '            End Try

        '            'catch mysql server connection Errors
        '        Catch myerror As MySqlException
        '            MessageBox.Show("Error connecting to the database: " & myerror.Message)

        '            'if the connection is not closed close it
        '        Finally
        '            If mysqlServer.State <> ConnectionState.Closed Then mysqlServer.Close()
        '        End Try

        '        'clear p
        '        p = 0

        '        'add the assignment names to lstassignment
        '        While (assignmentnames.Count > p)
        '            lstAssignment.Items.Add(assignmentnames.Item(p))

        '            'incrament the variable
        '            p += 1
        '        End While

        '    End If


    End Sub

    Private Sub showCollected()
        ''add  students names that turned somthing in for the selected assignment
        ''belived to not be working properly ---- 12/19/09 - TS


        'Dim mysqlServer As MySqlConnection
        'Dim myCommand As New MySqlCommand
        'Dim assignmentSQL As String
        'Dim assignmentnames As New List(Of String)
        'Dim assignmentid As Integer
        'Dim usersidthatsubmittedassingments As New List(Of String)
        'Dim usersthatsubmittedassingments As New List(Of String)
        'Dim usersinclass As New List(Of String)
        'Dim instanceid As Integer
        'Dim instanceidSQL As String
        'Dim classStudentsSQL As String

        'cmdCollected.BorderStyle = BorderStyle.Fixed3D
        'cmdMissing.BorderStyle = BorderStyle.FixedSingle

        'mysqlServer = New MySqlConnection() 'This needs to be able to be changed to what frmSettings.txtServer is saved to
        'mysqlServer.ConnectionString = frmSplash.SQLConnection1.getConnectionString

        'lstFeedback.Items.Clear()
        'If lstAssignment.SelectedIndex <> -1 Then


        '    assignmentSQL = "select id from mdl_assignment where name = """ & lstAssignment.Items.Item(lstAssignment.SelectedIndex) & """" & " and course = " & courseids(lstClass.SelectedIndex)
        '    Try
        '        mysqlServer.Open()
        '        Try
        '            myCommand.Connection = mysqlServer
        '            myCommand.CommandText = assignmentSQL
        '            Dim reader As MySqlDataReader
        '            reader = myCommand.ExecuteReader()
        '            While reader.Read()
        '                assignmentid = reader.GetString(0)
        '            End While
        '            reader.Close()
        '            assignmentSQL = "select userid from mdl_assignment_submissions where assignment =" & assignmentid
        '            myCommand.Connection = mysqlServer
        '            myCommand.CommandText = assignmentSQL
        '            reader = myCommand.ExecuteReader()
        '            While reader.Read()
        '                usersidthatsubmittedassingments.Add(reader.GetString(0))
        '            End While
        '            reader.Close()
        '            instanceidSQL = "select id from mdl_context where contextlevel= 50 and instanceid = " & courseids.Item(lstClass.SelectedIndex)
        '            myCommand.Connection = mysqlServer
        '            myCommand.CommandText = instanceidSQL
        '            reader = myCommand.ExecuteReader()
        '            While reader.Read()
        '                instanceid = reader.GetString(0)
        '            End While
        '            reader.Close()
        '            classStudentsSQL = "select userid from mdl_role_assignments where contextid = " & instanceid
        '            myCommand.Connection = mysqlServer
        '            myCommand.CommandText = classStudentsSQL
        '            reader = myCommand.ExecuteReader()
        '            While reader.Read()
        '                usersinclass.Add(reader.GetString(0))
        '            End While
        '            reader.Close()

        '            Dim g As Integer
        '            g = 0

        '            While g < usersidthatsubmittedassingments.Count
        '                assignmentSQL = "select firstname , lastname from mdl_user where id =" & usersidthatsubmittedassingments.Item(g)
        '                myCommand.Connection = mysqlServer
        '                myCommand.CommandText = assignmentSQL
        '                reader = myCommand.ExecuteReader()
        '                While reader.Read()
        '                    usersthatsubmittedassingments.Add(reader.GetString(0) & " " & reader.GetString(1))
        '                End While
        '                reader.Close()
        '                g += 1
        '            End While

        '        Catch myerror As MySqlException
        '            MsgBox("There was an error reading from the database: " & myerror.Message)
        '        End Try
        '    Catch myerror As MySqlException
        '        MessageBox.Show("Error connecting to the database: " & myerror.Message)
        '        frmSettings.Show()
        '        Dim errString As String
        '        errString = "An error occured either while trying to connect to the specified server, " & Chr(13) & Chr(10) & "or your stored credentials are invald." & Chr(13) & Chr(10) & Chr(13) & Chr(10) & "Please review your connection settings and try again."
        '        MsgBox(errString, MsgBoxStyle.OkOnly & MsgBoxStyle.Critical, "Auto-login Failure")
        '    Finally
        '        If mysqlServer.State <> ConnectionState.Closed Then mysqlServer.Close()
        '    End Try
        '    Dim p As Integer
        '    p = 0
        '    Dim f As Integer
        '    f = 0
        '    Dim h As Integer
        '    h = 0
        '    ' MsgBox(usersinclass.Count)
        '    'MsgBox(usersidthatsubmittedassingments.Count)
        '    While (usersinclass.Count > f)
        '        h = 0
        '        While (usersidthatsubmittedassingments.Count > h)
        '            ' MsgBox("h= " & h)
        '            'MsgBox("f= " & f)
        '            If (usersinclass.Item(f) = usersidthatsubmittedassingments(h)) Then
        '                lstFeedback.Items.Add(usersthatsubmittedassingments.Item(h))
        '            End If
        '            h += 1
        '        End While
        '        f += 1
        '    End While
        '    'MsgBox("after h= " & h)
        '    ' MsgBox("after f= " & f)
        'End If
    End Sub

    Private Sub cmdDownload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdDownload.Click
        'downloads all of the submitted files for the assignment
        'TODO -- 
        'remove all SQL refrances
        'and change to PHP calls
        '


        'show all the students the turned in the assignment
        Call showCollected()

        'holds the SQL server connection
        'Dim mysqlServer As MySqlConnection

        'holds the SQL query before execution and handles command execution
        'Dim myCommand As New MySqlCommand



        'holds the assignment names
        Dim assignmentnames As New List(Of String)




        'holds the assignment instance id
        Dim assignmentinstanceid As String = ""

        'holds the fullname of the students that submitted
        Dim userFULLNAMEsubmitter As New List(Of String)

        'holds the regkey for the savepath
        Dim regKey As RegistryKey

        'create a new mysqlconnection object
        'mysqlServer = New MySqlConnection()

        'set the connection string to the one defined in frmSplash
        'mysqlServer.ConnectionString = frmSplash.SQLConnection1.getConnectionString

        'sets the progress bar back to 0
        progressBar.Value = progressBar.Minimum


        'disables everything on the form and makes the curser a waiting curser
        lstClass.Enabled = False
        lstAssignment.Enabled = False
        'cmdCollected.Enabled = False
        'cmdMissing.Enabled = False
        'cmdGrade.Enabled = False
        cmdDownload.Enabled = False
        Me.Cursor = Cursors.WaitCursor


        'set the SQL command
        'assignmentSQL = "select id from mdl_assignment where name = """ & lstAssignment.Items.Item(lstAssignment.SelectedIndex) & """" & " and course = " & courseids(lstClass.SelectedIndex)

        'Try

        '    'open the SQL connection to the server
        '    mysqlServer.Open()

        '    Try

        '        'set the SQL query and assign the mysql server connection that it will be executed on
        '        myCommand.Connection = mysqlServer
        '        myCommand.CommandText = assignmentSQL

        '        'create a mysql data reader and execute it
        '        Dim reader As MySqlDataReader
        '        reader = myCommand.ExecuteReader()

        '        'read the results of the SQL query
        '        While reader.Read()
        '            assignmentid = reader.GetString(0)
        '        End While

        '        'close the reader
        '        reader.Close()

        '        'set the SQL command
        '        assignmentinstanceidSQL = "select id from mdl_course_modules where course = " & courseids(lstClass.SelectedIndex) & " and instance = " & assignmentid

        '        'set the SQL query
        '        myCommand.CommandText = assignmentinstanceidSQL

        '        'execute the command and prepare to read the results
        '        reader = myCommand.ExecuteReader()

        '        'read the results of the SQL query
        '        While reader.Read()
        '            assignmentinstanceid = reader.GetString(0)
        '        End While

        '        'close the reader
        '        reader.Close()

        '        'close the mysql connection
        '        mysqlServer.Close()

        '        'catch all reader errors
        '    Catch myerror As MySqlException
        '        MsgBox("There was an error reading from the database: " & myerror.Message)
        '    End Try

        '    'catch mysql server connection Errors
        'Catch myerror As MySqlException
        '    MessageBox.Show("Error connecting to the database: " & myerror.Message)

        '    'if the connection is not closed close it
        'Finally
        '    If mysqlServer.State <> ConnectionState.Closed Then mysqlServer.Close()
        'End Try



        Dim p As Integer
        p = 0
        Dim f As Integer
        f = 0
        Dim h As Integer
        h = 0

        'loginToMoodle()


        Dim Method As HTTPMethod = HTTPMethod.HTTP_POST

        Dim ContentType As String = ""
        Dim Response As HttpWebResponse
        Dim SR As StreamReader
        Dim ResponseData As String


        Dim URL1 As String
        Dim URL2 As String
        Dim counter As Integer
        Dim counter1 As Integer
        counter = 0
        counter1 = 0


        'get the Regkey for the default save location--- note this should be taken out of here and done before this
        regKey = Registry.CurrentUser.OpenSubKey("software\moodle\settings")
        Dim savepath As String
        savepath = regKey.GetValue("savepath") & "\"
        If savepath.Equals("\") Then
            savepath = "C:\Data\"
        End If

        Dim g As New IO.DirectoryInfo(savepath & lstClass.Items.Item(lstClass.SelectedIndex) & "\" & lstAssignment.Items.Item(lstAssignment.SelectedIndex))

        If (g.Exists) Then


            If (MsgBox("Warning!!, This Assignment Folder already Exists, Do you really want to Overwrite?", MsgBoxStyle.YesNo, "Warning") = MsgBoxResult.No) Then
                Me.Cursor = Cursors.Default
                lstClass.Enabled = True
                lstAssignment.Enabled = True
                'cmdCollected.Enabled = True
                'cmdMissing.Enabled = True
                'cmdGrade.Enabled = True
                cmdDownload.Enabled = True
                cmdFinshed.Enabled = True
                cmdFinshed.ForeColor = Color.Black

                Exit Sub
            End If

        End If


        'if the class directory and assignment directory are not made make them
        Try
            Directory.CreateDirectory(savepath & lstClass.Items.Item(lstClass.SelectedIndex) & "\" & lstAssignment.Items.Item(lstAssignment.SelectedIndex))
        Catch
        End Try


        'set the URL that lists the submissions
        URL1 = frmSplash.regsettings.getSvrURL & "mod/assignment/submissions_extern.php?id=" & courses.Item(lstClass.SelectedIndex).getassignmentlist.Item(lstAssignment.SelectedIndex).getassignmentid

        'create a new request with the URL that list submissions
        Dim request As HttpWebRequest = WebRequest.Create(URL1)

        'holds a list of submitted files
        Dim files As New String("")

        'sets the HTTP Method to get
        Method = HTTPMethod.HTTP_POST
        request.Method = Method.ToString().Substring(5)

        Dim PostData As String = ""

        'set the authentication cookies
        request.CookieContainer = New CookieContainer
        request.CookieContainer.Add(frmSplash.httplog.cookies)
        If (Method = HTTPMethod.HTTP_POST AndAlso PostData <> "" AndAlso ContentType = "") Then
            ContentType = "application/x-www-form-urlencoded"
        End If

        If (ContentType <> "") Then
            request.ContentType = ContentType
            request.ContentLength = PostData.Length
        End If
        request.ContentLength = 0
        'turn off keepalive
        request.KeepAlive = False

        Try
            'get response
            Response = request.GetResponse()
            SR = New StreamReader(Response.GetResponseStream())
            files = SR.ReadToEnd()
            SR.Close()
            Response.Close()
        Catch Wex As System.Net.WebException
            SR = New StreamReader(Wex.Response.GetResponseStream())
            ResponseData = SR.ReadToEnd()
            MsgBox("Something bad happend : " & ResponseData)
        End Try

        'holds the list of seperated file name


        'general counter veriables
        Dim i As Integer

        '
        Dim start As Integer = 0
        Dim endo As Integer = 0

        i = 0



        Dim filenames As New List(Of String)(files.Split("`"))
        Dim Fullnames As New List(Of String)
        Dim studentid As New List(Of String)
        Dim filenamed As New List(Of String)
        Dim Submittedfile As New List(Of String)



        While (filenames.Count > i + 1)

            Dim parts As New List(Of String)(filenames.Item(i).Split(","))

            Fullnames.Add(parts.Item(0))
            studentid.Add(parts.Item(1))

            If (parts.Count > 2) Then
                filenamed.Add(parts.Item(2))
                Submittedfile.Add("True")
            Else
                Submittedfile.Add("false")
            End If

            i += 1

        End While

        i = 0


        'delete the users who did not submit
        While (Submittedfile.Count > i)
            If (Submittedfile.Item(i) = "false") Or filenamed.Item(i) = "" Then
                Fullnames.RemoveAt(i)
                studentid.RemoveAt(i)
                filenamed.RemoveAt(i)
                Submittedfile.RemoveAt(i)
                i -= 1
            End If
            i += 1
        End While



        'for each user get all of there files
        While (studentid.Count > counter)

            'set urls for the right user
            URL2 = frmSplash.regsettings.getSvrURL & "file.php?file=/"
            'URL2 = URL2 & courses.Item(lstClass.SelectedIndex).getid & "/moddata/assignment/" & courses.Item(lstClass.SelectedIndex).getassignmentlist.Item(lstAssignment.SelectedIndex).getassignmentid & "/" & studentid.Item(counter) & "/"
            'MsgBox(courses.Item(lstClass.SelectedIndex).getassignmentlist.Item(lstAssignment.SelectedIndex).getassignmentid)
            'MsgBox(courses.Item(lstClass.SelectedIndex).getassignmentlist.Item(lstAssignment.SelectedIndex).getassignmentname)


            'make the approprate directory
            Try
                Directory.CreateDirectory(savepath & lstClass.Items.Item(lstClass.SelectedIndex) & "\" & lstAssignment.Items.Item(lstAssignment.SelectedIndex) & "\" & Fullnames.Item(counter))
            Catch
            End Try


            'holds the file stream
            Dim aFileStream As FileStream

            'reset the counter on each iteration
            i = 0

            filenamed.Item(counter) = filenamed.Item(counter).Substring(0, filenamed.Item(counter).Length - 1)

            'if there are multiple files
            If (filenamed.Item(counter).Contains(Chr(64))) Then

                'untill there no commas
                While (filenamed.Item(counter).Contains(Chr(64)))

                    'for each filename
                    While (filenamed.Item(counter).Split(Chr(64)).Count > i)

                        'open a filestream to the local save directory
                        aFileStream = New FileStream(savepath & lstClass.Items.Item(lstClass.SelectedIndex) & "\" & lstAssignment.Items.Item(lstAssignment.SelectedIndex) & "\" & Fullnames.Item(counter) & "\" & filenamed.Item(counter).Split(Chr(64)).ElementAt(i).Split("/").ElementAt(filenamed.Item(counter).Split(Chr(64)).ElementAt(i).Split("/").Count - 1), FileMode.OpenOrCreate, FileAccess.Write)

                        'open a bianry stream to the previous filestream location
                        Dim myBinaryWriter As New BinaryWriter(aFileStream)

                        'get file and write it to the file
                        myBinaryWriter.Write(GetURLDataBin(URL2 & filenamed.Item(counter).Split(Chr(64)).GetValue(i)))
                        myBinaryWriter.Close()

                        'incrament
                        i += 1
                    End While

                    'set current filenames to blank
                    filenamed.Item(counter) = ""
                End While

                'if there is only one files
            Else

                'open a filestream to the local save directory
                aFileStream = New FileStream(savepath & lstClass.Items.Item(lstClass.SelectedIndex) & "\" & lstAssignment.Items.Item(lstAssignment.SelectedIndex) & "\" & Fullnames.Item(counter) & "\" & filenamed.Item(counter).Split("/").ElementAt(filenamed.Item(counter).Split("/").Count - 1), FileMode.OpenOrCreate, FileAccess.Write)

                'open a bianry stream to the previous filestream location
                Dim myBinaryWriter As New BinaryWriter(aFileStream)

                'get file and write it to the file
                myBinaryWriter.Write(GetURLDataBin(URL2 & filenamed.Item(counter)))
                myBinaryWriter.Close()
            End If

            counter += 1

            'After the file is written, the progressBar will increase by a certain step based on it's size 
            'in relation to the total number of users
            Dim pbsizestep As Integer
            pbsizestep = (Int(progressBar.Maximum() / studentid.Count))
            progressBar.Increment(pbsizestep)

        End While

        'make sure the progress bar is at max
        progressBar.Value = progressBar.Maximum

        'unlock the form
        Me.Cursor = Cursors.Default
        lstClass.Enabled = True
        lstAssignment.Enabled = True
        'cmdCollected.Enabled = True
        'cmdMissing.Enabled = True
        'cmdGrade.Enabled = True
        cmdDownload.Enabled = True
        cmdFinshed.Enabled = True
        cmdFinshed.ForeColor = Color.Black
    End Sub

    Private Sub cmdCollected_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        'show students that submitted something
        'Call showCollected()
    End Sub

    Private Sub cmdMissing_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        'Dim mysqlServer As MySqlConnection
        'Dim myCommand As New MySqlCommand
        'Dim assignmentSQL As String
        'Dim assignmentnames As New List(Of String)
        'Dim assignmentid As Integer
        'Dim usersidthatsubmittedassingments As New List(Of String)
        'Dim usersthatsubmittedassingments As New List(Of String)
        'Dim usersinclass As New List(Of String)
        'Dim instanceid As Integer
        'Dim instanceidSQL As String
        'Dim classStudentsSQL As String
        'Dim usersinclassthatsubmmitedassignment As New List(Of String)
        'Dim usersinclassthathavenotsubmmitedassignment As New List(Of String)
        'Dim firstnamelastname As New List(Of String)
        'Dim g As Integer
        'g = 0

        'cmdCollected.BorderStyle = BorderStyle.FixedSingle
        'cmdMissing.BorderStyle = BorderStyle.Fixed3D

        'mysqlServer = New MySqlConnection() 'This needs to be able to be changed to what frmSettings.txtServer is saved to
        'mysqlServer.ConnectionString = frmSplash.SQLConnection1.getConnectionString
        'lstFeedback.Items.Clear()


        'If lstAssignment.SelectedIndex <> -1 Then


        '    assignmentSQL = "select id from mdl_assignment where name = """ & lstAssignment.Items.Item(lstAssignment.SelectedIndex) & """" & " and course = " & courseids(lstClass.SelectedIndex)

        '    Try
        '        mysqlServer.Open()
        '        Try
        '            myCommand.Connection = mysqlServer
        '            myCommand.CommandText = assignmentSQL
        '            Dim reader As MySqlDataReader
        '            reader = myCommand.ExecuteReader()
        '            While reader.Read()
        '                assignmentid = reader.GetString(0)
        '            End While
        '            reader.Close()

        '            assignmentSQL = "select userid from mdl_assignment_submissions where assignment =" & assignmentid

        '            myCommand.Connection = mysqlServer
        '            myCommand.CommandText = assignmentSQL
        '            reader = myCommand.ExecuteReader()

        '            While reader.Read()
        '                usersidthatsubmittedassingments.Add(reader.GetString(0))
        '            End While
        '            reader.Close()

        '            instanceidSQL = "select id from mdl_context where contextlevel= 50 and instanceid = " & courseids.Item(lstClass.SelectedIndex)


        '            myCommand.Connection = mysqlServer
        '            myCommand.CommandText = instanceidSQL
        '            reader = myCommand.ExecuteReader()

        '            While reader.Read()
        '                instanceid = reader.GetString(0)
        '            End While
        '            reader.Close()


        '            classStudentsSQL = "select userid from mdl_role_assignments where contextid = " & instanceid

        '            myCommand.Connection = mysqlServer
        '            myCommand.CommandText = classStudentsSQL
        '            reader = myCommand.ExecuteReader()

        '            While reader.Read()
        '                usersinclass.Add(reader.GetString(0))
        '            End While
        '            reader.Close()
        '            While g < usersidthatsubmittedassingments.Count
        '                assignmentSQL = "select firstname , lastname from mdl_user where id =" & usersidthatsubmittedassingments.Item(g)
        '                myCommand.Connection = mysqlServer
        '                myCommand.CommandText = assignmentSQL
        '                reader = myCommand.ExecuteReader()
        '                While reader.Read()
        '                    usersthatsubmittedassingments.Add(reader.GetString(0) & " " & reader.GetString(1))
        '                End While
        '                reader.Close()
        '                g += 1
        '            End While
        '        Catch myerror As MySqlException
        '            MsgBox("There was an error reading from the database: " & myerror.Message)
        '        End Try
        '    Catch myerror As MySqlException
        '        MessageBox.Show("Error connecting to the database: " & myerror.Message)
        '        frmSettings.Show()
        '        Dim errString As String
        '        errString = "An error occured either while trying to connect to the specified server, " & Chr(13) & Chr(10) & "or your stored credentials are invald." & Chr(13) & Chr(10) & Chr(13) & Chr(10) & "Please review your connection settings and try again."
        '        MsgBox(errString, MsgBoxStyle.OkOnly & MsgBoxStyle.Critical, "Auto-login Failure")
        '    Finally
        '        If mysqlServer.State <> ConnectionState.Closed Then mysqlServer.Close()
        '    End Try
        '    Dim p As Integer
        '    p = 0
        '    Dim f As Integer
        '    f = 0
        '    Dim h As Integer
        '    h = 0
        '    ' MsgBox(usersinclass.Count)
        '    'MsgBox(usersidthatsubmittedassingments.Count)
        '    While (usersinclass.Count > f)
        '        h = 0
        '        While (usersidthatsubmittedassingments.Count > h)
        '            ' MsgBox("h= " & h)
        '            'MsgBox("f= " & f)
        '            If (usersinclass.Item(f) = usersidthatsubmittedassingments(h)) Then
        '                usersinclassthatsubmmitedassignment.Add(usersidthatsubmittedassingments.Item(h))
        '            End If
        '            h += 1
        '        End While
        '        f += 1
        '    End While
        '    'MsgBox("after h= " & h)
        '    ' MsgBox("after f= " & f)

        '    h = 0
        '    f = 0
        '    'MsgBox(usersinclass.Count)
        '    ' MsgBox(usersinclassthatsubmmitedassignment.Count)
        '    While (usersinclass.Count > h)
        '        f = 0
        '        While (usersinclassthatsubmmitedassignment.Count > f)
        '            'MsgBox("h= " & h)
        '            ' MsgBox("f= " & f)
        '            If (usersinclassthatsubmmitedassignment.Item(f) = usersinclass.Item(h)) Then
        '                usersinclass.RemoveAt(h)
        '            End If
        '            f += 1
        '        End While
        '        h += 1
        '    End While
        '    h = 0
        '    mysqlServer = New MySqlConnection() 'This needs to be able to be changed to what frmSettings.txtServer is saved to
        '    mysqlServer.ConnectionString = frmSplash.SQLConnection1.getConnectionString
        '    lstFeedback.Items.Clear()
        '    g = 0
        '    While (g < usersinclass.Count)
        '        Try
        '            mysqlServer.Open()
        '            Try
        '                assignmentSQL = "select firstname , lastname from mdl_user where id =" & usersinclass.Item(g)
        '                Dim reader As MySqlDataReader
        '                myCommand.Connection = mysqlServer
        '                myCommand.CommandText = assignmentSQL

        '                reader = myCommand.ExecuteReader()

        '                While reader.Read()
        '                    firstnamelastname.Add(reader.GetString(0) & " " & reader.GetString(1))
        '                End While
        '                reader.Close()
        '                g += 1
        '            Catch myerror As MySqlException
        '                MsgBox("There was an error reading from the database: " & myerror.Message)
        '            End Try
        '        Catch myerror As MySqlException
        '            MessageBox.Show("Error connecting to the database: " & myerror.Message)
        '            frmSettings.Show()
        '            Dim errString As String
        '            errString = "An error occured either while trying to connect to the specified server, " & Chr(13) & Chr(10) & "or your stored credentials are invald." & Chr(13) & Chr(10) & Chr(13) & Chr(10) & "Please review your connection settings and try again."
        '            MsgBox(errString, MsgBoxStyle.OkOnly & MsgBoxStyle.Critical, "Auto-login Failure")
        '        Finally
        '            If mysqlServer.State <> ConnectionState.Closed Then mysqlServer.Close()
        '        End Try
        '    End While
        '    While (firstnamelastname.Count > h)
        '        lstFeedback.Items.Add(firstnamelastname.Item(h))
        '        h += 1
        '    End While
        'End If
    End Sub

    Public Function GetURLDataBin(ByVal URL As String) As Byte()
        'Recives binary data from the internet

        'holds the web request
        Dim Req As HttpWebRequest

        'holds the file
        Dim SourceStream As System.IO.Stream

        'holds the repsonse data from te server
        Dim Response1 As HttpWebResponse

        'create a new webrequest with the passed URL
        Req = WebRequest.Create(URL)

        ' Disables KeepAlive as it can cause problems with opening lots of connections
        Req.KeepAlive = False


        'create a new cookie container to hold the authentication information
        Req.CookieContainer = New CookieContainer

        'add the cookies the the request
        Req.CookieContainer.Add(frmSplash.httplog.cookies)


        'opens the connection
        Response1 = Req.GetResponse()

        'assignes the connection to a stream reader
        SourceStream = Response1.GetResponseStream()


        'SourceStream has no ReadAll, so we must read data block-by-block  
        'Temporary Buffer and block size  
        Dim Buffer(4096) As Byte, BlockSize As Integer

        'Memory stream to store data  
        Dim TempStream As New MemoryStream
        Do
            BlockSize = SourceStream.Read(Buffer, 0, 4096)
            If BlockSize > 0 Then TempStream.Write(Buffer, 0, BlockSize)
        Loop While BlockSize > 0

        'close the stream and response
        SourceStream.Close()
        Response1.Close()

        'return the document binary data  
        Return TempStream.ToArray()


    End Function

    Private Sub lstAssignment_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles lstAssignment.SelectedIndexChanged
        progressBar.Value = progressBar.Minimum
        'Enables or disables the download button if lstassignment has somthing selected
        'if there is an assignment selected it will show the students that turned somthing in

        'is somthing selected?
        If lstAssignment.SelectedIndex <> -1 Then
            cmdDownload.Enabled = True
            cmdDownload.ForeColor = Color.Black
        Else
            cmdDownload.Enabled = False
            cmdDownload.ForeColor = Color.DimGray
        End If
        Call showCollected()
    End Sub

    'Public Sub loginToMoodle()
    '    'this subrutine logs the current user into the moodle
    '    'this rutine sends two requests to the server the first is just used to get the cookies required to login

    '    'what we need to send to the server so we can get logged in
    '    Dim PostData As String = "username=admin&password=clawhammer&testcookies=1"

    '    'calculate the length of the post data
    '    Dim bytArguments As Byte() = System.Text.Encoding.ASCII.GetBytes(PostData)

    '    'we dont have a content type defined
    '    Dim ContentType As String = ""

    '    'holds the response that the server sends back
    '    Dim Response As HttpWebResponse

    '    'a streamWriter
    '    Dim SW As StreamWriter

    '    'a streamReader
    '    Dim SR As StreamReader

    '    'holds some response data
    '    Dim ResponseData As String




    '    'first request
    '    'will not login the user
    '    'needs cookies first
    '    'url of the home page of the moodle
    '    Dim request As HttpWebRequest = WebRequest.Create(frmSplash.regsettings.getSvrURL & "index.php")

    '    'were going to do a post
    '    Dim Method As HTTPMethod = HTTPMethod.HTTP_POST

    '    'need keepalive off so we dont have issues
    '    request.KeepAlive = False
    '    request.CookieContainer = New CookieContainer()


    '    ' Prepare Request Object
    '    request.Method = Method.ToString().Substring(5)

    '    'Set form/post content-type if necessary
    '    If (Method = HTTPMethod.HTTP_POST AndAlso PostData <> "" AndAlso ContentType = "") Then
    '        ContentType = "application/x-www-form-urlencoded"
    '    End If

    '    'Set Content-Type
    '    If (ContentType <> "") Then
    '        request.ContentType = ContentType
    '        request.ContentLength = bytArguments.Length
    '    End If

    '    'Send Request, If Request
    '    If (Method = HTTPMethod.HTTP_POST) Then
    '        Try
    '            SW = New StreamWriter(request.GetRequestStream())
    '            SW.Write(PostData)
    '            SW.Close()

    '        Catch Ex As Exception
    '            MsgBox("Somthing Bad Happened")
    '        End Try
    '    End If


    '    ' Receive Response
    '    Try
    '        Response = request.GetResponse()
    '        cookies = Response.Cookies
    '        SR = New StreamReader(Response.GetResponseStream())
    '        ResponseData = SR.ReadToEnd()
    '        SR.Close()

    '        Response.Close()
    '    Catch Wex As System.Net.WebException
    '        SR = New StreamReader(Wex.Response.GetResponseStream())
    '        ResponseData = SR.ReadToEnd()
    '        MsgBox("Somthing Bad Happened" & ResponseData)
    '    End Try




    '    'now that we have the cookies
    '    'we can send them and get authenticated
    '    Dim request2 As HttpWebRequest = WebRequest.Create(frmSplash.regsettings.getSvrURL & "login/index.php")


    '    ' Prepare Request Object
    '    request2.Method = Method.ToString().Substring(5)


    '    ' Set form/post content-type if necessary
    '    If (Method = HTTPMethod.HTTP_POST AndAlso PostData <> "" AndAlso ContentType = "") Then
    '        ContentType = "application/x-www-form-urlencoded"
    '    End If

    '    ' Set Content-Type
    '    If (ContentType <> "") Then
    '        request2.ContentType = ContentType
    '        request2.ContentLength = PostData.Length
    '    End If

    '    'the moodle uses 3 cookies
    '    request2.CookieContainer = New CookieContainer
    '    request2.CookieContainer.Add(cookies.Item(0))
    '    request2.CookieContainer.Add(cookies.Item(1))
    '    request2.CookieContainer.Add(cookies.Item(2))

    '    'add the cookies to the public variable
    '    cookies.Add(cookies.Item(0))
    '    cookies.Add(cookies.Item(1))
    '    cookies.Add(cookies.Item(2))

    '    'once again turn off keepalive
    '    request2.KeepAlive = False

    '    ' Send Request, If Request
    '    If (Method = HTTPMethod.HTTP_POST) Then
    '        Try
    '            SW = New StreamWriter(request2.GetRequestStream())
    '            SW.Write(PostData)
    '            SW.Close()
    '        Catch Ex As Exception
    '            MsgBox("Somthing Bad Happened")
    '        End Try
    '    End If

    '    ' Receive Response
    '    Try

    '        Response = request2.GetResponse()
    '        SR = New StreamReader(Response.GetResponseStream())
    '        ResponseData = SR.ReadToEnd()
    '        SR.Close()
    '        Response.Close()

    '    Catch Wex As System.Net.WebException
    '        SR = New StreamReader(Wex.Response.GetResponseStream())
    '        ResponseData = SR.ReadToEnd()
    '        MsgBox("Somthing Bad Happened" & ResponseData)
    '    End Try
    'End Sub

End Class

